package com.intelligentmeterreadingsys.checkwork.activity;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.httpserver.HttpClientServer;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.service.TimingLocationService;
import com.intelligentmeterreadingsys.util.DateUtil;
import com.intelligentmeterreadingsys.util.SafetyExitUtil;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;

import dbhelper.XmlNameHelper;

/**
 * 上下班考勤
 * 
 * @author king
 * 
 */
public class CheckWorkMainActivity extends Activity implements BDLocationListener {

    public static final String username = "USERNAME";// 存取用户名称标志

    public SafetyExitUtil safe = null;

    public static final String workstatus = "WORKSTATUS";// 上班状态

    public EditText edit1;// 用户姓名

    public EditText edit2;// 用户密码

    public Button button1;// 上班

    public Button button2;// 下班

    public AlertDialog pd;

    public boolean status = false;

    public String Latitude;

    public String Longitude;

    public SharedPreferenceUtil sp = null;

    public LocationClient client;

    public long time;

    public String request = "上班";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);
	setContentView(R.layout.checkworkmain);

	// 解决android 4.0Http请求问题
	StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
	StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath().build());
	initLocation();
	inti();
	addListent();

    }

    /**
     * 初始化
     */
    public void inti() {
	edit1 = (EditText) findViewById(R.id.checkwork_username);
	edit2 = (EditText) findViewById(R.id.checkwork_pass);
	button1 = (Button) findViewById(R.id.gotowork);
	button2 = (Button) findViewById(R.id.gooffwork);
	sp = new SharedPreferenceUtil(this);
	pd = new ProgressDialog(CheckWorkMainActivity.this);

	String name = sp.getValue(username);
	sp.getBoolean(workstatus);

	if (!TextUtils.isEmpty(name)) {
	    edit1.setText(name);
	}
    }

    /**
     * 添加上下班事件
     */
    public void addListent() {

	// 上班事件
	button1.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		boolean bo = openGPSSettings();
		if (!bo) {
		    return;
		}
		request = "上班";
		Date d = new Date();
		time = d.getTime();
		SharedPreferenceUtil sp = new SharedPreferenceUtil(CheckWorkMainActivity.this);
		boolean b = sp.getBoolean(workstatus);
		if (b) {
		    Toast.makeText(CheckWorkMainActivity.this, "今天已打过上班卡", Toast.LENGTH_LONG).show();
		    finish();
		    return;
		}

		status = true;
		pd.setTitle(null);
		pd.setMessage("GPS定位中...");
		pd.show();

		client.start();

	    }
	});

	// 下班事件
	button2.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		// 关闭自动定位服务
		Intent intent = new Intent(CheckWorkMainActivity.this, TimingLocationService.class);
		stopService(intent);
		request = "下班";
		Date d = new Date();
		time = d.getTime();
		SharedPreferenceUtil sp = new SharedPreferenceUtil(CheckWorkMainActivity.this);
		boolean b = sp.getBoolean(workstatus);
		if (!b) {
		    Toast.makeText(CheckWorkMainActivity.this, "还没打上班卡！", Toast.LENGTH_LONG).show();
		    finish();
		    return;
		}
		status = false;
		pd.setTitle(null);
		pd.setMessage("GPS定位中...");
		pd.show();
		System.out.println("show");
		if (client != null && !client.isStarted()) {
		    client.start();
		}

	    }
	});
    }

    /**
     * 初始化定位
     */
    public void initLocation() {
	client = new LocationClient(this);
	LocationClientOption option = new LocationClientOption();
	// 打开GPS
	option.setOpenGps(true);
	// 设置坐标类型
	option.setCoorType("bd09ll");

	// 设置网络优先
	// option.setPriority(LocationClientOption.GpsFirst);
	option.setPriority(LocationClientOption.NetWorkFirst);

	// 设置产品线名称
	option.setProdName("waterSys");

	// 设置定位定时时间
	option.setScanSpan(5000);
	client.setLocOption(option);
	client.registerLocationListener(this);

    }

    @Override
    protected void onDestroy() {
	System.out.println("onDestroy");
	if (client != null && client.isStarted()) {
	    client.stop();
	    client = null;
	}

	super.onDestroy();
    }

    public void getLoDoubles(BDLocation location) {

	System.out.println("得到径维度");
	if (location != null) {
	    pd.setMessage("登录服务器中......");
	    SharedPreferenceUtil sh = new SharedPreferenceUtil(this);
	    sh.insertValue(XmlNameHelper.LATITUDE, location.getLatitude() + "");
	    sh.insertValue(XmlNameHelper.LONGITUDE, location.getLongitude() + "");
	    this.Latitude = location.getLatitude() + "";
	    this.Longitude = location.getLongitude() + "";
	    work(request);
	}
	Date d = new Date();
	if ((d.getTime() - time) > 16000) {
	    this.Latitude = "0";
	    this.Longitude = "0";
	    pd.setMessage("登录服务器中......");
	    work(request);
	}

    }

    /**
     * 向服务端发请求
     * 
     * @param request
     */
    public void work(String status) {
	client.stop();

	// 得到网络服务
	HttpClientServer server = new HttpClientServer(this);

	// 上班传给后台参数
	Map<String, String> map = new HashMap<String, String>();

	map.put("name", edit1.getEditableText().toString());
	map.put("pass", edit2.getEditableText().toString());
	map.put("latitude", Latitude);
	map.put("longitude", Longitude);
	map.put("status", status);
	SharedPreferenceUtil sh = new SharedPreferenceUtil(this);

	map.put("imsi", sh.getValue(XmlNameHelper.IMSI));
	map.put("date", DateUtil.getBeforeDay(0));
	String respon = server.doPost(map, RequestUrl.GOTOWORK);
	System.out.println("返回信息" + respon);
	if (!respon.equals("error")) {
	    pd.cancel();

	    try {
		System.out.println(respon);
		JSONObject js = new JSONObject(respon);

		String s = js.getString("message");
		if (s.equals("no")) {
		    Toast.makeText(CheckWorkMainActivity.this, "密码或用户名错误", Toast.LENGTH_LONG).show();
		    return;
		} else if (s.equals("yes")) {
		    Toast.makeText(CheckWorkMainActivity.this, "打卡成功", Toast.LENGTH_LONG).show();
		    // 把用户名字存入XML
		    sp.insertValue(username, edit1.getEditableText().toString());
		    // 更新上下班状态

		    sp = new SharedPreferenceUtil(CheckWorkMainActivity.this);
		    SharedPreferenceUtil sp = new SharedPreferenceUtil(CheckWorkMainActivity.this);
		    if (request.equals("上班")) {
			Intent intent = new Intent(CheckWorkMainActivity.this, TimingLocationService.class);
			startService(intent);
			sp.insertValue(workstatus, true);
		    } else {
			Intent intent = new Intent(CheckWorkMainActivity.this, TimingLocationService.class);
			stopService(intent);
			sp.insertValue(workstatus, false);
		    }

		    finish();
		}
	    } catch (JSONException e) {
		Toast.makeText(CheckWorkMainActivity.this, "密码或用户名错误", Toast.LENGTH_LONG).show();
		return;

	    }

	} else {
	    Toast.makeText(CheckWorkMainActivity.this, "网络连接错误，请检查", Toast.LENGTH_LONG).show();
	    pd.cancel();

	}

    }

    @Override
    protected void onPause() {

	safe = new SafetyExitUtil(CheckWorkMainActivity.this);
	safe.start();

	super.onPause();
    }

    @Override
    protected void onResume() {
	if (safe != null) {
	    safe.stop();
	}

	super.onResume();
    }

    /**
     * 判断GPS是否存在或开启
     */
    public boolean openGPSSettings() {
	LocationManager alm = (LocationManager) getSystemService(this.LOCATION_SERVICE);
	if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
	    return true;
	}
	Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
	Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
	return false;
    }

    @Override
    public void onReceiveLocation(BDLocation location) {
	System.out.println("-------------------");
	getLoDoubles(location);

    }

    @Override
    public void onReceivePoi(BDLocation arg0) {
	// TODO Auto-generated method stub

    }

}
